#!/usr/bin/env node

/**
 * 系统演示启动脚本
 * 自动化完成系统启动和演示准备
 */

const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');

// 颜色输出工具
const colors = {
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
  white: '\x1b[37m',
  reset: '\x1b[0m',
  bright: '\x1b[1m'
};

function colorLog(color, ...args) {
  console.log(colors[color] + args.join(' ') + colors.reset);
}

function header(text) {
  const line = '='.repeat(50);
  colorLog('cyan', '\n' + line);
  colorLog('cyan', colors.bright + text.toUpperCase());
  colorLog('cyan', line);
}

function step(text) {
  colorLog('blue', '🔄 ' + text);
}

function success(text) {
  colorLog('green', '✅ ' + text);
}

function error(text) {
  colorLog('red', '❌ ' + text);
}

function warning(text) {
  colorLog('yellow', '⚠️  ' + text);
}

function info(text) {
  colorLog('white', 'ℹ️  ' + text);
}

// 检查系统依赖
async function checkDependencies() {
  step('检查系统依赖...');
  
  const dependencies = [
    { name: 'Node.js', command: 'node --version' },
    { name: 'npm', command: 'npm --version' },
    { name: 'Docker', command: 'docker --version' },
    { name: 'Docker Compose', command: 'docker-compose --version' }
  ];

  for (const dep of dependencies) {
    try {
      const result = await runCommand(dep.command, { silent: true });
      success(`${dep.name}: ${result.trim()}`);
    } catch (err) {
      error(`${dep.name} 未安装或不可用`);
      process.exit(1);
    }
  }
}

// 执行命令的辅助函数
function runCommand(command, options = {}) {
  return new Promise((resolve, reject) => {
    const [cmd, ...args] = command.split(' ');
    const child = spawn(cmd, args, {
      stdio: options.silent ? 'pipe' : 'inherit',
      shell: true
    });

    let output = '';
    if (options.silent && child.stdout) {
      child.stdout.on('data', (data) => {
        output += data.toString();
      });
    }

    child.on('close', (code) => {
      if (code === 0) {
        resolve(output);
      } else {
        reject(new Error(`Command failed: ${command}`));
      }
    });
  });
}

// 检查项目文件
function checkProjectStructure() {
  step('检查项目结构...');
  
  const requiredFiles = [
    'docker-compose.yml',
    'backend/package.json',
    'frontend/package.json',
    'blockchain/package.json'
  ];

  const missingFiles = requiredFiles.filter(file => !fs.existsSync(file));
  
  if (missingFiles.length > 0) {
    error('缺少必要文件:');
    missingFiles.forEach(file => console.log(`   - ${file}`));
    process.exit(1);
  }
  
  success('项目结构检查完成');
}

// 启动Docker服务
async function startDockerServices() {
  step('启动Docker服务...');
  
  // 检查是否已有运行的容器
  try {
    await runCommand('docker-compose ps', { silent: true });
    info('检测到现有Docker服务，将重新启动...');
    await runCommand('docker-compose down');
  } catch (err) {
    // 如果没有现有服务，这是正常的
  }

  // 启动服务
  info('启动基础服务（数据库+后端+前端）...');
  await runCommand('docker-compose up -d mongodb backend frontend');
  
  success('Docker服务启动完成');
}

// 等待服务就绪
async function waitForServices() {
  step('等待服务启动...');
  
  const services = [
    { name: '数据库', url: 'http://localhost:27017', maxWait: 30 },
    { name: '后端API', url: 'http://localhost:3000/api/v1/health', maxWait: 60 },
    { name: '前端界面', url: 'http://localhost:8080', maxWait: 45 }
  ];

  for (const service of services) {
    await waitForService(service.name, service.url, service.maxWait);
  }
  
  success('所有服务已就绪');
}

// 等待单个服务
async function waitForService(name, url, maxWait) {
  info(`等待 ${name} 就绪...`);
  
  const startTime = Date.now();
  const timeout = maxWait * 1000;
  
  while (Date.now() - startTime < timeout) {
    try {
      if (url.includes('27017')) {
        // MongoDB特殊检查
        await runCommand('docker-compose exec -T mongodb mongosh --eval "db.adminCommand(\'ping\')"', { silent: true });
      } else {
        // HTTP服务检查
        await runCommand(`curl -f ${url}`, { silent: true });
      }
      success(`${name} 已就绪`);
      return;
    } catch (err) {
      // 继续等待
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
  
  error(`${name} 启动超时`);
  process.exit(1);
}

// 初始化演示数据
async function initializeDemoData() {
  step('初始化演示数据...');
  
  try {
    // 运行演示数据脚本
    await runCommand('node scripts/demo-data.js');
    success('演示数据初始化完成');
  } catch (err) {
    warning('演示数据初始化失败，跳过此步骤');
    warning('您可以稍后手动运行: node scripts/demo-data.js');
    // 不终止进程，继续显示系统信息
  }
}

// 显示系统信息
function showSystemInfo() {
  header('系统演示信息');
  
  colorLog('green', '🌐 访问地址:');
  console.log('   前端界面: http://localhost:8080');
  console.log('   后端API:  http://localhost:3000');
  console.log('   健康检查: http://localhost:3000/api/v1/health');
  
  colorLog('green', '\n👥 演示账号:');
  console.log('┌───────────────┬────────────────────┬─────────────┬────────────┐');
  console.log('│ 用户名        │ 邮箱               │ 密码        │ 角色       │');
  console.log('├───────────────┼────────────────────┼─────────────┼────────────┤');
  console.log('│ admin         │ admin@teatrace.com │ admin123    │ 管理员     │');
  console.log('│ farmer_zhang  │ zhang@farm.com     │ farmer123   │ 农民       │');
  console.log('│ logistics_li  │ li@logistics.com   │ logistics123│ 物流       │');
  console.log('│ merchant_wang │ wang@shop.com      │ merchant123 │ 商家       │');
  console.log('│ consumer_liu  │ liu@email.com      │ consumer123 │ 消费者     │');
  console.log('└───────────────┴────────────────────┴─────────────┴────────────┘');
  
  colorLog('green', '\n📦 演示批次:');
  console.log('   TEA2024001 - 西湖龙井 (已销售)');
  console.log('   TEA2024002 - 安溪铁观音 (运输中)');
  console.log('   TEA2024003 - 云南普洱 (已加工)');
  
  colorLog('green', '\n🔧 管理命令:');
  console.log('   查看日志: docker-compose logs -f');
  console.log('   重启服务: docker-compose restart');
  console.log('   停止服务: docker-compose down');
  console.log('   查看状态: docker-compose ps');
  
  colorLog('green', '\n✨ 演示流程建议:');
  console.log('   1. 使用admin账号登录系统管理界面');
  console.log('   2. 切换到不同角色体验功能差异');
  console.log('   3. 创建新的茶叶批次并更新状态');
  console.log('   4. 使用公共查询功能验证溯源信息');
  console.log('   5. 查看区块链交易记录（如果启用）');
  
  colorLog('yellow', '\n⚠️  注意事项:');
  console.log('   - 首次启动可能需要较长时间下载Docker镜像');
  console.log('   - 确保端口8080和3000未被其他程序占用');
  console.log('   - 演示数据会在每次重新初始化时重置');
  
  colorLog('magenta', '\n🎯 准备完成，开始演示吧！');
}

// 主函数
async function main() {
  try {
    header('区块链茶叶溯源系统演示启动');
    
    await checkDependencies();
    checkProjectStructure();
    await startDockerServices();
    await waitForServices();
    await initializeDemoData();
    
    showSystemInfo();
    
  } catch (err) {
    console.error('\n');
    error('演示启动失败:');
    console.error(err);
    process.exit(1);
  }
}

// 处理中断信号
process.on('SIGINT', async () => {
  console.log('\n');
  warning('收到中断信号，正在清理...');
  try {
    await runCommand('docker-compose down');
    info('服务已停止');
  } catch (err) {
    // 忽略清理错误
  }
  process.exit(0);
});

// 启动脚本
if (require.main === module) {
  main();
}

module.exports = {
  checkDependencies,
  startDockerServices,
  waitForServices,
  initializeDemoData
};